using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;
using InfoSoftGlobal;

public partial class ChartAndReport : System.Web.UI.Page
{
    SQLInteract objSqlIntract = new SQLInteract();
    generateChart objGC = new generateChart();
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Page.Title = "Defect Dashboard";
        objSqlIntract.OpenNewConnection();
        CheckAllDefectReason.Attributes.Add("onclick", "checkAllDefects(this);");
        CheckAllProject.Attributes.Add("onclick", "checkAllProject(this);");
        
        if (!IsPostBack)
        {
            pnlCBdefectReason.Visible = false;
            pnlProject.Visible = false;
            pnlDefectReason.Visible = false;
            pnlTestCasePhase.Visible = false;
            pnlButtonForChart.Visible = false;
            pnlChatMenu.Visible = false;
            fillReleaseDropDown();
        }
      
    }
    
    public void fillReleaseDropDown()
    {
        try
        {
            string selectRelease = "select distinct Detected_In_Release from Defects order by Detected_In_Release desc";
            DataSet dsRelease = new DataSet();
            dsRelease = objSqlIntract.ReturnDataAdapter(selectRelease);
            ddlRelease.DataSource = dsRelease;
            ddlRelease.DataTextField = "Detected_In_Release";
            ddlRelease.DataValueField = "Detected_In_Release";
            ddlRelease.DataBind();
            
        }
        catch(Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" >alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {

        }
    }

    //public void bindDateDropdown()
    //{
    //    try
    //    {
    //        string selectDateFromTo = "select distinct Detected_on_Date_From, Detected_on_Date_To from Defects order by DefectID ";
    //        DataSet dsDateFromTo = new DataSet();
    //        dsDateFromTo = objSqlIntract.ReturnDataAdapter(selectDateFromTo);
    //        ddlStartDate.DataSource = dsDateFromTo.Tables[0].Rows[0][0].ToString();
    //        ddlStartDate.DataTextField = "Detected_on_Date_From";
    //        ddlRelease.DataSource = dsDateFromTo.Tables[0].Rows[0][1].ToString();
    //        ddlRelease.DataTextField = "Detected_In_Release";
    //        ddlRelease.DataValueField = "Detected_In_Release";
    //        ddlRelease.DataBind();

    //    }
    //    catch (Exception ex)
    //    {
    //        this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" >alert(\"Error: " + ex.Message + "\");</script>", false);
    //    }
    //    finally
    //    {

    //    }
    //}
    protected void getProjects(object sender, EventArgs e)
    {
        pnlProject.Visible = true;
        pnlDefectReason.Visible = true;
        pnlTestCasePhase.Visible = true;
        pnlButtonForChart.Visible = true;
        string selectedRelease = ddlRelease.SelectedValue.ToString().Trim();
        DataSet dsProjectList = objSqlIntract.ReturnDataAdapter("Select distinct(Project) from Defects where Detected_In_Release='" + selectedRelease + "' order by Project");
        if (dsProjectList.Tables.Count > 0)
        {
            cbProjects.DataSource = dsProjectList;
            cbProjects.DataTextField = "Project";
            cbProjects.DataValueField = "Project";
            cbProjects.DataBind();
            divContainer.Visible = true;
        }
    }
    protected void rbDefectReason_CheckedChanged(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            pnlCBdefectReason.Visible = true;
            cbDefectReason.Visible = true;
            string selectedTestPhase = rbDefectReason.SelectedValue.ToString().Trim();
            string selectReasonQ = "SELECT distinct [Status_Reason] FROM [AvivaTPortal].[dbo].[Defects] where [Detected_In_Cycle] like '%" + selectedTestPhase.Trim() + "%'order by Status_Reason ";
            DataSet dsDefectReason = objSqlIntract.ReturnDataAdapter(selectReasonQ);

            if (dsDefectReason.Tables.Count > 0)
            {
                cbDefectReason.DataSource = dsDefectReason;
                cbDefectReason.DataTextField = "Status_Reason";
                cbDefectReason.DataValueField = "Status_Reason";
                cbDefectReason.DataBind();
                
            }
        }

    }
    protected void btnCreateChart_Click(object sender, EventArgs e)
    {
        RenderChart();
        divContainer.Visible = false;
    }
    protected void MenuChart_MenuItemClick(object sender, MenuEventArgs e)
    {
        int index = Int32.Parse(e.Item.Value);
        MultiView_Chart.ActiveViewIndex = index;
        RenderChart();
    }

    protected void pnlLoad(object sender, EventArgs e)
    {

    }
    public void prepareProjectBarChart(string selectQuery, string release_name, string project_list, string test_phases)
    {
        Table DynTable = new Table();
        DynTable.ID = "lnkchart";
        DynTable.BorderWidth = 0;
        DynTable.CellPadding = 0;
        DynTable.CellPadding = 0;
        SqlDataReader sdr;
        sdr = objSqlIntract.ReturnDataReader(selectQuery);

        int count = 0;
        string projectList1 = "";

        int statusClosed = 0;
        string statusClosedList = "";
        Array statusClosedarray;

        int statusReopen = 0;
        string statusReopenList = "";
        Array statusReopenarray;

        int statusOpen = 0;
        string statusOpenList = "";
        Array statusOpenarray;

        int statusNew = 0;
        string statusNewList = "";
        Array statusNewarray;

        int statusFixed = 0;
        string statusFixedList = "";
        Array statusFixedarray;

        string projectList = "";

        if (sdr.HasRows)
        {
            while (sdr.Read())
            {
                TableCell tbcell1 = new TableCell();
                TableCell tbcell2 = new TableCell();
                TableCell tbcell3 = new TableCell();
                TableCell tbcell4 = new TableCell();
                TableRow tbRow = new TableRow();
                //project array
                if (projectList1 == "" || sdr["Project"].ToString().Trim() != projectList1)
                {
                    projectList = projectList.Trim().ToString() + sdr["Project"].ToString().Trim() + ",";
                    tbcell1.Text = sdr["Project"].ToString().Trim();
                    tbcell2.Text = "&nbsp;&nbsp;<a href=\"#\" onclick=\"javascript: open_piechart('" + sdr["Project"].ToString().Trim() + "','" + release_name + "',0);\">Defect By Priority</a>";
                    tbcell3.Text = "&nbsp;&nbsp;<a href=\"#\" onclick=\"javascript: open_piechart('" + sdr["Project"].ToString().Trim() + "','" + release_name + "',1);\">Defect By Team</a>";
                    tbcell4.Text = "&nbsp;&nbsp;<a href=\"#\" onclick=\"javascript: open_piechart('" + sdr["Project"].ToString().Trim() + "','" + release_name + "',2);\">Defect Summary</a>";
                    tbRow.Cells.Add(tbcell1);
                    tbRow.Cells.Add(tbcell2);
                    tbRow.Cells.Add(tbcell3);
                    tbRow.Cells.Add(tbcell4);
                    DynTable.Rows.Add(tbRow);
                }

                if (sdr["Project"].ToString().Trim() != projectList1 && projectList1 != "")
                {
                    statusClosedList = statusClosedList + statusClosed.ToString().Trim() + ",";
                    statusReopenList = statusReopenList + statusReopen.ToString().Trim() + ",";
                    statusOpenList = statusOpenList + statusOpen.ToString().Trim() + ",";
                    statusNewList = statusNewList + statusNew.ToString().Trim() + ",";
                    statusFixedList = statusFixedList + statusFixed.ToString().Trim() + ",";
                    statusReopen = 0;
                    statusOpen = 0;
                    statusClosed = 0;
                    statusNew = 0;
                    statusFixed = 0;
                }

                if (sdr["Status"].ToString().Trim() == "Closed")
                {
                    statusClosed = statusClosed + 1;
                }

                if (sdr["Status"].ToString().Trim() == "Reopen")
                {
                    statusReopen = statusReopen + 1;
                }

                if (sdr["Status"].ToString().Trim() == "New")
                {
                    statusNew = statusNew + 1;
                }

                if (sdr["Status"].ToString().Trim() == "Open")
                {
                    statusOpen = statusOpen + 1;
                }

                if (sdr["Status"].ToString().Trim() == "Fixed")
                {
                    statusFixed = statusFixed + 1;
                }

                projectList1 = sdr["Project"].ToString().Trim();
                count = count + 1;
            }
              
            
            divtblproj.Controls.Add(DynTable);
            statusClosedList = statusClosedList + statusClosed.ToString().Trim() + ",";
            statusReopenList = statusReopenList + statusReopen.ToString().Trim() + ",";
            statusOpenList = statusOpenList + statusOpen.ToString().Trim() + ",";
            statusNewList = statusNewList + statusNew.ToString().Trim() + ",";
            statusFixedList = statusFixedList + statusFixed.ToString().Trim() + ",";
        }
        statusClosedarray = statusClosedList.Split(new char[] { ',' });
        statusFixedarray = statusFixedList.Split(new char[] { ',' });
        statusOpenarray = statusOpenList.Split(new char[] { ',' });
        statusReopenarray = statusReopenList.Split(new char[] { ',' });
        statusNewarray = statusNewList.Split(new char[] { ',' });
        string strXMLChart = objGC.GenerateBarChartXML(project_list, statusClosedarray, statusOpenarray, statusNewarray, statusFixedarray, statusReopenarray, release_name);
        fcLiteral.Text = FusionCharts.RenderChart("FusionCharts/FCF_MSColumn3D.swf", "", strXMLChart, "myNext", "800", "500", false, false);

        fcLiteral.Visible = true;
    }

    public void prepareDefectTrendChart(string queryTrendChart, string release_list, string testPhase, string defectList)
    {
        
        SqlDataReader sdr, sdr1 = null;
        Array statusClosedarray;
        Array statusReopenarray;
        ArrayList arrDates = new ArrayList();
        
        int statusClosed = 0;
        string statusClosedList = "";

        int statusReopen = 0;
        string statusReopenList = "";
        string queryDefect = "select distinct(Detected_on_Date_From) from Defects where Detected_In_Release in (" + release_list + ") and  Detected_In_Cycle like '%" + testPhase + "%' and Status_Reason in (" + defectList + ")  order by Detected_on_Date_From";
        sdr = objSqlIntract.ReturnDataReader(queryTrendChart);
        if (sdr.HasRows)
        {
            while (sdr.Read())
            {
                arrDates.Add(DateTime.Parse(sdr["Detected_on_Date_From"].ToString()).ToString("MM/dd/yyyy"));
            }
        }

        foreach (string item in arrDates)
        {
            if (item != "")
            {
                statusClosed = 0;
                statusReopen = 0;
                sdr1 = objSqlIntract.ReturnDataReader("select * from Defects where Detected_on_Date_From <= '" + item + "' and  Detected_In_Release like '%" + release_list + "%' and  Detected_In_Cycle like '%" + testPhase + "%'and Status_Reason in (" + defectList + ") order by Detected_on_Date_From");
                if (sdr1.HasRows)
                {
                    while (sdr1.Read())
                    {
                        if (sdr1["Status"].ToString().Trim() == "Closed")
                        {
                            statusClosed = statusClosed + 1;
                        }
                        else
                        {
                            statusReopen = statusReopen + 1;
                        }
                    }
                    statusClosedList = statusClosedList + statusClosed.ToString().Trim() + ",";
                    statusReopenList = statusReopenList + statusReopen.ToString().Trim() + ",";
                }
            }
        }
        statusClosedarray = statusClosedList.Split(new char[] { ',' });
        statusReopenarray = statusReopenList.Split(new char[] { ',' });

        string strXML1 = objGC.TrendChartXMLForDefectReason(arrDates, statusClosedarray, statusReopenarray, release_list);
        litDefectReson.Text = FusionCharts.RenderChart("FusionCharts/FCF_MSLine.swf", "", strXML1, "myNext", "800", "500", false, false);
        litDefectReson.Visible = true;
    }
    public void prepareTestPhaseTrendChart(string queryDefect, string release_list, string testPhase)
    {

        SqlDataReader sdrTH, sdrTH1 = null;
        Array statusClosedarrayTH;
        Array statusReopenarrayTH;
        ArrayList arrDatesTH = new ArrayList();

        int statusClosedTH = 0;
        string statusClosedListTH = "";

        int statusReopenTH = 0;
        string statusReopenListTH = "";
        //string queryDefect = "select distinct(Detected_on_Date_From) from Defects where Detected_In_Release in (" + release_list + ") and  Detected_In_Cycle like '%" + testPhase.ToString().Trim() + "%'  order by Detected_on_Date_From";
        sdrTH = objSqlIntract.ReturnDataReader(queryDefect);
        if (sdrTH.HasRows)
        {
            while (sdrTH.Read())
            {
                arrDatesTH.Add(DateTime.Parse(sdrTH["Detected_on_Date_From"].ToString()).ToString("MM/dd/yyyy"));
            }
        }

        foreach (string item in arrDatesTH)
        {
            if (item != "")
            {
                statusClosedTH = 0;
                statusReopenTH = 0;
                sdrTH1 = objSqlIntract.ReturnDataReader("select * from Defects where Detected_on_Date_From <= '" + item + "' and  Detected_In_Release like '%" + release_list + "%' and  Detected_In_Cycle like '%" + testPhase + "%'  order by Detected_on_Date_From");
                if (sdrTH1.HasRows)
                {
                    while (sdrTH1.Read())
                    {
                        if (sdrTH1["Status"].ToString().Trim() == "Closed")
                        {
                            statusClosedTH = statusClosedTH + 1;
                        }
                        else
                        {
                            statusReopenTH = statusReopenTH + 1;
                        }
                    }
                    statusClosedListTH = statusClosedListTH + statusClosedTH.ToString().Trim() + ",";
                    statusReopenListTH = statusReopenListTH + statusReopenTH.ToString().Trim() + ",";
                }
            }
        }
        statusClosedarrayTH = statusClosedListTH.Split(new char[] { ',' });
        statusReopenarrayTH = statusReopenListTH.Split(new char[] { ',' });

        string strXMLTH1 = objGC.TrendChartXMLTestPhase(arrDatesTH, statusClosedarrayTH, statusReopenarrayTH, release_list);
        litTestPhase.Text = FusionCharts.RenderChart("FusionCharts/FCF_MSLine.swf", "", strXMLTH1, "myNext", "800", "500", false, false);
        litTestPhase.Visible = true;

    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        if (IsPostBack)
        {
            if (divContainer.Visible == false)
            {
                divContainer.Visible = true;
                ibHideShowDiv.ImageUrl = "images/plus.png";
            }
            else
            {
                divContainer.Visible = false;
                ibHideShowDiv.ImageUrl = "images/minus.png";
            }
            //divtblproj.Visible = true;
            RenderChart();
        }
    }
    public void RenderChart()
    {
        //Select Release Name
        string releaseName = ddlRelease.SelectedValue.ToString().Trim();
        //read Test Phases rado button value value
        string testPhase = rbTestCasePhase.SelectedValue.ToString().Trim();
        //read Invalid Defect Reason Against Test Phases
        string testPhaseDefect = rbDefectReason.SelectedValue.ToString().Trim();
        //Select all checked Projects list
        StringBuilder sbProjectList = new StringBuilder("");
        int ProjectCount = cbProjects.Items.Count;

        for (int i = 0; i < ProjectCount; i++)
        {
            if (cbProjects.Items[i].Selected)
            {
                if (sbProjectList.Length == 0)
                {
                    sbProjectList.Append("'");
                    sbProjectList.Append(cbProjects.Items[i].Text.ToString().Trim());
                    sbProjectList.Append("'");
                }
                else
                {
                    sbProjectList.Append(",");
                    sbProjectList.Append("'");
                    sbProjectList.Append(cbProjects.Items[i].Text.ToString().Trim());
                    sbProjectList.Append("'");
                }
            }
        }
        //get all checked defect reason value
        StringBuilder sbDefectsReason = new StringBuilder("");
        int defectReasonCount = cbDefectReason.Items.Count;
        for (int i = 0; i < defectReasonCount; i++)
        {
            if (cbDefectReason.Items[i].Selected)
            {
                if (sbDefectsReason.Length == 0)
                {
                    sbDefectsReason.Append("'");
                    sbDefectsReason.Append(cbDefectReason.Items[i].Text.ToString().Trim());
                    sbDefectsReason.Append("'");
                }
                else
                {
                    sbDefectsReason.Append(",");
                    sbDefectsReason.Append("'");
                    sbDefectsReason.Append(cbDefectReason.Items[i].Text.ToString().Trim());
                    sbDefectsReason.Append("'");
                }
            }
        }
        string project_list = sbProjectList.ToString().Trim();
        string defect_reason = sbDefectsReason.ToString().Trim();
        if (project_list == "" && defect_reason == "" && testPhase == "")
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Please Select at least one critria to generate graph \");</script>", false);
            return;
        }
        if (project_list != "")
        {
            string queryProjects = "select DefectID,Project,Status,Detected_In_Release,System_Detected_In from Defects where Detected_In_Release like '%" + releaseName + "%' and Project in(" + project_list + " ) order by Project";
            prepareProjectBarChart(queryProjects, releaseName, project_list, testPhase);
            pnlChatMenu.Visible = true;
        }
        if (defect_reason != "")
        {
            string queryDefectResaon = "select distinct(Detected_on_Date_From) from Defects where Status_Reason in (" + defect_reason + ") and Detected_In_Release like '%" + releaseName + "%' and  Detected_In_Cycle like '%" + testPhaseDefect + "%'  order by Detected_on_Date_From";
            prepareDefectTrendChart(queryDefectResaon, releaseName, testPhaseDefect, defect_reason);
            pnlChatMenu.Visible = true;
        }
        if (testPhase != "")
        {
            string queryTestPhase = "select distinct(Detected_on_Date_From) from Defects where Detected_In_Release like '%" + releaseName + "%' and  Detected_In_Cycle like '%" + testPhaseDefect.ToString().Trim() + "%'  order by Detected_on_Date_From";
            prepareTestPhaseTrendChart(queryTestPhase, releaseName, testPhase);
            pnlChatMenu.Visible = true;
        }
    
    }
}
